package cn.zhangfusheng.api.explain;

import cn.zhangfusheng.api.annotation.ClassAnnotation;
import cn.zhangfusheng.api.config.ZfsApiConfig;
import cn.zhangfusheng.api.entity.ClassModel;
import cn.zhangfusheng.api.util.ReflexUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 类扫描注解解释
 *
 * @ClassName: ClassExplain
 * @Author: ZFS
 */
public class ClassExplain {

    /**
     * 解释
     *
     * @param group 组
     * @return ParameterModel
     */
    public static List<ClassModel> explain(String group) {
        String packagePath = null;
        try {
            packagePath = ZfsApiConfig.getGroupPackageMap(group);
        } catch (Exception e) {
            throw new RuntimeException("至少要配置一个要扫描的路径");
        }
        ArrayList<ClassModel> classResultModels = new ArrayList<>();
        List<Class<?>> classes = ReflexUtil.getClasses(packagePath);
        classes.forEach(clazz -> {
            ClassAnnotation clazzAnnotation = clazz.getAnnotation(ClassAnnotation.class);
            if (clazzAnnotation != null) {
                ClassModel classModel = initClassModel(clazzAnnotation, clazz);
                List<Method> mehods = ReflexUtil.getMehods(clazz);
                classModel.setMethodModels(MethodExplain.explain(mehods));
                classResultModels.add(classModel);
            }
        });
        return classResultModels;
    }

    private static ClassModel initClassModel(ClassAnnotation annotation, Class clazz) {
        ClassModel classModel = new ClassModel();
        String className = annotation.name();
        className =
                StringUtils.isBlank(className) ?
                        clazz.getName()
                                .replace(clazz.getPackage().getName(), "")
                                .replace(".", "")
                        : className;
        classModel.setName(className);
        classModel.setDesc(annotation.desc());
        classModel.setGroup(annotation.group());
        classModel.setHidden(annotation.hidden());
        String path = annotation.path();
        if (path.indexOf("/") == 0) {
            path = path.substring(1, path.length());
        }
        if (path.lastIndexOf("/") == path.length()) {
            path = path.substring(0, path.length() - 1);
        }
        classModel.setPath(path);
        return classModel;
    }
}
